package org.lucky.admin.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.lucky.admin.mapper.AdminMapper;
import org.lucky.admin.mapper.LoginInfoMapper;
import org.lucky.admin.service.IAdminService;
import org.lucky.admin.util.RedisUtil;
import org.lucky_common.domain.Admin;
import org.lucky_common.domain.InviteParam;
import org.lucky_common.domain.LoginInfo;
import org.lucky_common.dto.AdminDto;
import org.lucky_common.dto.LoginDto;
import org.lucky_common.util.AjaxResult;
import org.lucky_common.util.MD5Utils;
import org.lucky_common.util.RonghuaAssert;
import org.lucky_common.vo.AdminExportVo;
import org.lucky_common.vo.InviteExportVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements IAdminService {

    @Resource
    private RedisUtil redisUtil;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private LoginInfoMapper loginInfoMapper;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Resource
    private AdminMapper adminMapper;

    @Override
    public AjaxResult login(LoginDto loginDto, HttpServletRequest request) {
        String token = request.getHeader("Token");
        if (token != null){
            Boolean exists = redisUtil.exists(token);
            if (!exists) {
                redisTemplate.delete(token);
            }
        }
        AdminDto dto = new AdminDto();
        RonghuaAssert.isNotBlank(loginDto.getUsername(), "用户名不能为空");
        RonghuaAssert.isNotBlank(loginDto.getPassword(), "密码不能为空");
        LoginInfo logininfo = loginInfoMapper.queryByUserNameOrEmail(loginDto.getUsername());
        System.out.println(logininfo);
        RonghuaAssert.isNotNull(logininfo, "用户名或密码错误！");
        System.out.println(loginDto.getPassword());
        System.out.println(logininfo.getSalt());
        String pwd = MD5Utils.encrypByMd5(loginDto.getPassword() + logininfo.getSalt());
        System.out.println(pwd);
        assert pwd != null;
        RonghuaAssert.isEq(pwd, logininfo.getPassword(), "用户名或密码错误！");
        String userAgentStr = request.getHeader("user-agent");
        Admin employee = adminMapper.queryByLoginInfoId(logininfo.getId());
        //生成token
        String token2 = "";
        if (employee != null) {
            token2 = this.tokenService.generateToken(userAgentStr, loginDto.getUsername(), employee);
        }else {
            //生成token
            token2 = this.tokenService.generateToken(userAgentStr, loginDto.getUsername(), logininfo);
        }
        //组织前台需要的信息
        dto.setToken(token2);
        dto.setIsLogin(true);
        dto.setTokenCreatedDate(System.currentTimeMillis());
        dto.setTokenExpiryDate(System.currentTimeMillis() + 7200000);
        logininfo.setPassword("");
        logininfo.setSalt("");
        if (employee != null){
            employee.setPassword("");
            employee.setSalt("");
            dto.setUser(employee);
        }else {
            System.out.println(logininfo);
            dto.setEmployee(logininfo);
        }
        //保存token
        synchronized (AdminServiceImpl.class) {
            this.tokenService.save(token2, dto);
            this.tokenService.saveUser(loginDto.getUsername(), dto, token2);
        }
        return AjaxResult.success(dto);

    }

    @Override
    public List<AdminExportVo> getUserExportList() {
        List<Admin> users = this.list();
        //users集合转成export集合
        return users.stream().map(user -> {
            AdminExportVo vo = new AdminExportVo();
            BeanUtils.copyProperties(user, vo);
            return vo;
        }).collect(Collectors.toList());
    }

    @Override
    @Transactional
    public void saveAdmin(Admin employee) {
        String salt = "flyer"+ UUID.randomUUID().toString()+"001";
        employee.setSalt(salt);
        employee.setPassword(MD5Utils.encrypByMd5(employee.getPassword() + salt));
        LoginInfo loginInfo = new LoginInfo(null, employee.getUsername(), employee.getSalt(), employee.getPassword(), employee.getEmail(), 1, 1, employee.getHeadImage());
        loginInfoMapper.insert(loginInfo);
        employee.setLoginInfoId(loginInfo.getId());
        adminMapper.insert(employee);
    }
}
